package com.ysu.zyw.common.util;

import com.ysu.zyw.common.exception.SystemException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * FreeMarkerUtil provide an set of operation to freemarker.
 * this class is based on org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer
 * declared in spring-view.xml, that's is the user must inject an FreeMarkerConfigurer into this class
 * before you use it.
 * <p>
 * Created by ZeRur on 2016/1/17.
 *
 * @author yaowu.zhang
 */
public class FreeMarkerUtil {

    private static final Logger logger = LoggerFactory.getLogger(FreeMarkerUtil.class);

    /**
     * this must inject by user, otherwise this class can't work.
     */
    private static FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * process an freemarker template, return a processed string.
     *
     * @param templateName template name with prefix
     * @param dataMap      the data freemarker use
     * @return string
     */
    public static String render(String templateName, Map<String, Object> dataMap) {
        Assert.notNull(freeMarkerConfigurer, "null freemarker configurer is not allowed, you must inject an freemarker configurer" +
                "into this class, this freemarker configurer is generally declared in spring-view.xml.");
        try {
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
            StringWriter stringWriter = new StringWriter();
            template.process(dataMap, stringWriter);
            return stringWriter.getBuffer().toString();
        } catch (IOException | TemplateException e) {
            logger.error("FreeMarkerUtil - render - " + e.getMessage(), e);
            throw new SystemException(e);
        }
    }

}
